package com.jiuyou.storeController.appointment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.appointmentSet.vo.AppointmentVO;
import com.ruoyi.appointmentSet.vo.ClosesDateVO;
import com.ruoyi.appointmentSet.vo.SeveralWeekVO;
import com.ruoyi.appointmentSet.vo.TimeFramesVO;
import com.ruoyi.appointment.domain.Appointment;
import com.ruoyi.appointment.service.IAppointmentService;
import com.ruoyi.appointmentClose.domain.AppointmentClose;
import com.ruoyi.appointmentClose.service.IAppointmentCloseService;
import com.ruoyi.appointmentRecord.domain.AppointmentRecord;
import com.ruoyi.appointmentRecord.service.IAppointmentRecordService;
import com.ruoyi.appointmentSet.domain.AppointmentSet;
import com.ruoyi.appointmentSet.service.IAppointmentSetService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.technician.domain.StoreTechnician;
import com.ruoyi.technician.service.IStoreTechnicianService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 预约管理
 * 2022年7月26日16:51:41
 */
@RestController
@RequestMapping("/store/appointment")
@Api(tags = {"预约管理控制器"})
public class AppointmentStoreController extends StoreBaseController {
    @Autowired
    private IAppointmentService appointmentService;
    @Autowired
    private IAppointmentCloseService appointmentCloseService;
    @Autowired
    private IAppointmentRecordService appointmentRecordService;
    @Autowired
    private IAppointmentSetService appointmentSetService;
    @Autowired
    private IStoreTechnicianService storeTechnicianService;
    /**
     * 获取预约设置信息，
     * @return
     */
    @PostMapping("/appointmentSetInfo")
    public AjaxResult appointmentSetInfo(){



        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        //获取技师，如果不是技师登录则是门店登录
        StoreTechnician storeTechnician= getStoreTechnician();
        AppointmentSet appointmentSetQuery=new AppointmentSet();
        appointmentSetQuery.setTechnicianId(0L);
        if(storeTechnician!=null){
            //技师登录
            appointmentSetQuery.setTechnicianId(storeTechnician.getId());
        }
        appointmentSetQuery.setStoreId(storeId);
        List<AppointmentSet> appointmentSetList= appointmentSetService.selectAppointmentSetList(appointmentSetQuery);
        AppointmentVO res=new AppointmentVO();
        List<SeveralWeekVO> severalWeeks=new ArrayList<SeveralWeekVO>();


        List<ClosesDateVO> colseDate=new ArrayList<ClosesDateVO>();
        List<TimeFramesVO> timeFrames=new ArrayList<TimeFramesVO>();
        String appointmentState=DicConstants.SYS_N.getCode();
        if(appointmentSetList.size()>0){
            AppointmentSet appointmentSet=appointmentSetList.get(0);
            appointmentState=appointmentSet.getAppointmentState();
            String severalWeeksStr=  appointmentSet.getSeveralWeeksStr();
            if(!StringUtils.isEmpty(severalWeeksStr)){
                severalWeeks= JSONArray.parseArray(severalWeeksStr,SeveralWeekVO.class);
            }
           String colseDateStr= appointmentSet.getColseDateStr();
            if(!StringUtils.isEmpty(colseDateStr)){
                colseDate= JSONArray.parseArray(colseDateStr,ClosesDateVO.class);
            }
            String timeFrameStr= appointmentSet.getTimeFrameStr();
            if(!StringUtils.isEmpty(timeFrameStr)){
                timeFrames= JSONArray.parseArray(timeFrameStr,TimeFramesVO.class);
            }
        }else{
            List<SysDictData> listSeveralWeeks=  DictUtils.getDictCache("several_weeks");
            for (SysDictData listSeveralWeek : listSeveralWeeks) {
                SeveralWeekVO severalWeekVO=new SeveralWeekVO();
                severalWeekVO.setChecked(DicConstants.SYS_N.getCode());
                severalWeekVO.setWeekKye(listSeveralWeek.getDictValue());
                severalWeekVO.setWeekName(listSeveralWeek.getDictLabel());
                severalWeeks.add(severalWeekVO);
            }
        }
        res.setAppointmentState(appointmentState);
        res.setTimeFrames(timeFrames);
        res.setClosesDates(colseDate);
        res.setSeveralWeeks(severalWeeks);
        List<String> timeList=  time_sort.keySet().stream().collect(Collectors.toList());
        JSONObject jso=new JSONObject();
        jso.put("appointmentVO",res);
        jso.put("timeList",timeList);
        return AjaxResult.success(jso);
    }
    /**
     * 新增或删除预约设置
     * @return
     */
    @PostMapping("/appointmentEdit")
    public AjaxResult appointmentEdit(@RequestBody AppointmentVO appointmentVO){
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        //获取技师，如果不是技师登录则是门店登录
        StoreTechnician storeTechnician= getStoreTechnician();
        Long technicianId=0L;
        if(storeTechnician!=null){
            //技师登录
            technicianId=storeTechnician.getId();
        }
        Appointment appointmentQuery=new Appointment();
        appointmentQuery.setStoreId(storeId);
        appointmentQuery.setTechnicianId(technicianId);
        List<Appointment>  listHistory= appointmentService.selectAppointmentList(appointmentQuery);
        List<Long> delIds=listHistory.stream().map(Appointment::getId).collect(Collectors.toList());
        if(delIds.size()>0){
            //删除历史
            appointmentService.logicDeleteAppointment(delIds.toArray(new Long[delIds.size()]),DicConstants.BUSINESS_Business.getCode(), getStoreUser().getId());

        }
        /**
         * 周几可以预约
         */
        List<SeveralWeekVO>  severalWeekVOList= appointmentVO.getSeveralWeeks();
        /**
         * 可预约的时段
         */
        List<TimeFramesVO> timeFramesVOList= appointmentVO.getTimeFrames();
        //先将可预约的时段转成时段list
        Map<String,String> mapTime=new LinkedHashMap<String,String>();
        //根据可预约时段转成map去掉重复的
        for (TimeFramesVO timeFramesVO : timeFramesVOList) {

            timeFramesVOToMap(timeFramesVO,mapTime);

        }

        List<String> listTimeFrames=mapTime.keySet().stream().collect(Collectors.toList());
        List<Appointment> batchList=new ArrayList<Appointment>();
        Date now=new Date();
        //遍历插入最新的
        for (SeveralWeekVO severalWeekVO : severalWeekVOList) {
            if(DicConstants.SYS_Y.getCode().equals(severalWeekVO.getChecked())){
                for (String listTimeFrame : listTimeFrames) {
                    Appointment appointment=new Appointment();
                    appointment.setStoreId(storeId);
                    appointment.setTechnicianId(technicianId);
                    appointment.setTimeFrame(listTimeFrame);
                    appointment.setSeveralWeeks(severalWeekVO.getWeekKye());
                    appointment.setCreateTime(now);
//                    appointmentService.insertAppointment(appointment);
                    batchList.add(appointment);
                }
            }
        }
        appointmentService.batchAppointment(batchList);
        AppointmentClose appointmentCloseQuery=new AppointmentClose();
        appointmentCloseQuery.setStoreId(storeId);
        appointmentCloseQuery.setTechnicianId(technicianId);
        List<AppointmentClose> appointmentCloseList=appointmentCloseService.selectAppointmentCloseList(appointmentCloseQuery);
        List<Long> closeDelIds=appointmentCloseList.stream().map(AppointmentClose::getId).collect(Collectors.toList());
        if(closeDelIds.size()>0){
            appointmentCloseService.logicDeleteAppointmentClose(closeDelIds.toArray(new Long[closeDelIds.size()]),DicConstants.BUSINESS_Business.getCode(), getStoreUser().getId());
        }
        /**
         * 不可预约的日期
         */
        List<ClosesDateVO> closesDateVOList= appointmentVO.getClosesDates();
        for (ClosesDateVO closesDateVO : closesDateVOList) {
           AppointmentClose appointmentClose=new AppointmentClose();
           appointmentClose.setStartTime(DateUtils.dateTime(closesDateVO.getStartDate()));
           appointmentClose.setEndTime(DateUtils.dateTime(closesDateVO.getEndDate()));
           appointmentClose.setStoreId(storeId);
           appointmentClose.setTechnicianId(technicianId);
           appointmentCloseService.insertAppointmentClose(appointmentClose);
        }

        AppointmentSet appointmentSetQuery=new AppointmentSet();
        appointmentSetQuery.setTechnicianId(technicianId);
        appointmentSetQuery.setStoreId(storeId);
        List<AppointmentSet> appointmentSetList= appointmentSetService.selectAppointmentSetList(appointmentSetQuery);
        AppointmentSet appointmentSet=new AppointmentSet();
        if(appointmentSetList.size()>0){
            //已有
            appointmentSet.setId(appointmentSetList.get(0).getId());
        }
        appointmentSet.setSeveralWeeksStr(JSONArray.toJSONString(appointmentVO.getSeveralWeeks()));
        appointmentSet.setTimeFrameStr(JSONArray.toJSONString(appointmentVO.getTimeFrames()));
        appointmentSet.setColseDateStr(JSONArray.toJSONString(appointmentVO.getClosesDates()));
        appointmentSet.setAppointmentState(appointmentVO.getAppointmentState());
        if(null!=appointmentSet.getId()){
            appointmentSetService.updateAppointmentSet(appointmentSet);
        }else{
            appointmentSet.setStoreId(storeId);
            appointmentSet.setTechnicianId(technicianId);
            appointmentSetService.insertAppointmentSet(appointmentSet);
        }

        return AjaxResult.success("保存成功");
    }
//B端需要的接口
    //预约处理卡
//    预约列表

    /**
     * 预约处理预约信息
     * @param appointmentRecordId
     * @param platformRemark
     * @param appointmentStatus
     * @return
     */
    @PostMapping("/handleAppointment")
    public AjaxResult handleAppointment(Long appointmentRecordId,String platformRemark,String appointmentStatus){
        AppointmentRecord appointmentRecord= appointmentRecordService.selectAppointmentRecordById(appointmentRecordId);
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        if(appointmentRecord.getStoreId()!=storeId){
            return AjaxResult.unAuthorize();
        }

        AppointmentRecord appointmentRecordUpdate=new AppointmentRecord();
        appointmentRecordUpdate.setId(appointmentRecordId);
        appointmentRecordUpdate.setPlatformRemark(platformRemark);
        appointmentRecordUpdate.setAppointmentStatus(appointmentStatus);
        appointmentRecordService.updateAppointmentRecord(appointmentRecordUpdate);
        JSONObject jso=new JSONObject();
        jso.put("appointmentStatusStr", DictUtils.getDictLabel("appointment_status",appointmentStatus));
        jso.put("msg","处理成功");
        return AjaxResult.success(jso);
    }

    /**
     * 返回列表的查询条件
     * @return
     */
    @PostMapping("/listRecordInfo")
    public AjaxResult listRecordInfo() {
        StoreTechnician storeTechnician= getStoreTechnician();
        boolean isTechnician=false;
        Long technicianId=null;
        if(storeTechnician!=null){
            //技师登录
            isTechnician=true;
            technicianId=storeTechnician.getId();
        }
        //所有技师
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();

        StoreTechnician storeTechnicianParam=new StoreTechnician();
        storeTechnicianParam.setStoreId(storeId);
        storeTechnicianParam.setState(DicConstants.SYS_Y.getCode());
        List<StoreTechnician> storeTechnicianList = storeTechnicianService.selectStoreTechnicianList(storeTechnicianParam);
        JSONArray technicianQueryList=new JSONArray();
        JSONObject jsoAll=new JSONObject();
        jsoAll.put("id","");
        jsoAll.put("techName","全部技师");
        technicianQueryList.add(jsoAll);
        for (StoreTechnician technician : storeTechnicianList) {
            JSONObject jso=new JSONObject();
            jso.put("id",technician.getId());
            jso.put("techName",technician.getTechName());
            technicianQueryList.add(jso);
        }
        //所有日期
        List<String> dateList=  appointmentRecordService.appointmentDistinct(storeId,technicianId);
        JSONArray dateQueryList=new JSONArray();
        JSONObject jsoAlld=new JSONObject();
        jsoAlld.put("id","");
        jsoAlld.put("label","全部日期");
        dateQueryList.add(jsoAlld);
        for (String s : dateList) {
            JSONObject jso=new JSONObject();
            s=s.substring(0,10);
            jso.put("id",s);
            jso.put("label",s);
            dateQueryList.add(jso);
        }

        JSONObject jso=new JSONObject();
        jso.put("isTechnician",isTechnician?"Y":"N");
        jso.put("technicianQueryList",technicianQueryList);
        jso.put("dateQueryList",dateQueryList);

        return AjaxResult.success(jso);
    }
    /**
     * 预约记录,商家和技师使用同一个
     * @return
     */
    @PostMapping("/listRecord")
    public AjaxResult listRecord(Long technicianId,String appointmentDate,String appointmentStatus) {

        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        StoreTechnician storeTechnician= getStoreTechnician();
//        Long technicianId=0L;
        if(storeTechnician!=null){
            //技师登录
            technicianId=storeTechnician.getId();
        }
        AppointmentRecord appointmentRecordQuery=new AppointmentRecord();
        appointmentRecordQuery.setStoreId(storeId);
        appointmentRecordQuery.setTechnicianId(technicianId);
        appointmentRecordQuery.setAppointmentStatus(appointmentStatus);
        if(!StringUtils.isEmpty(appointmentDate)){
            appointmentRecordQuery.getParams().put("beginAppointmentTime",appointmentDate);
            appointmentRecordQuery.getParams().put("endAppointmentTime",appointmentDate);
        }
        startPage();
        List<AppointmentRecord>  appointmentRecordList=appointmentRecordService.selectAppointmentRecordList(appointmentRecordQuery);
        TableDataInfo tableDataInfo= getDataTable(appointmentRecordList);
        List<Long> technicianIds=appointmentRecordList.stream().map(AppointmentRecord::getTechnicianId).collect(Collectors.toList());
        Map<Long,String> mapTechName=new HashMap<Long,String>();
        if(technicianIds.size()>0){
            StoreTechnician storeTechnicianQuery=new StoreTechnician();
            storeTechnicianQuery.getParams().put("technicianIds",technicianIds);
            List<StoreTechnician> storeTechnicianList=  storeTechnicianService.selectStoreTechnicianList(storeTechnicianQuery);
            mapTechName=storeTechnicianList.stream().collect(Collectors.toMap(StoreTechnician::getId,StoreTechnician::getTechName));
        }

        List<JSONObject> rows=new ArrayList<JSONObject>();
        for (AppointmentRecord appointmentRecord : appointmentRecordList) {
            JSONObject jso=new JSONObject();
            jso.put("id",appointmentRecord.getId());
            jso.put("storeImg",appointmentRecord.getStoreImg());
            jso.put("appointmentName",appointmentRecord.getAppointmentName());
            jso.put("appointmentPhone",appointmentRecord.getAppointmentPhone());
            jso.put("createTime",DateUtils.dateTimeYMDHSM(appointmentRecord.getCreateTime()));
            Long appointmentTechnicianId=appointmentRecord.getTechnicianId();
            String technicianName="";
            if(appointmentTechnicianId==0){
                technicianName="到店分配";
            }else{
                technicianName=mapTechName.get(appointmentTechnicianId);
            }
            jso.put("technicianName",technicianName);
            jso.put("appointmentItem",appointmentRecord.getAppointmentItem());
            jso.put("appointmentNum",appointmentRecord.getAppointmentNum());
            jso.put("appointmentTime", DateUtils.dateTime(appointmentRecord.getAppointmentTime()) +" "+ DictUtils.getDictLabel("several_weeks",appointmentRecord.getSeveralWeeks())+" "+appointmentRecord.getTimeFrame());
            jso.put("appointmentRemark",appointmentRecord.getAppointmentRemark());
            jso.put("platformRemark",appointmentRecord.getPlatformRemark());
            jso.put("appointmentStatus",appointmentRecord.getAppointmentStatus());
            jso.put("appointmentStatusStr", DictUtils.getDictLabel("appointment_status",appointmentRecord.getAppointmentStatus()));

            rows.add(jso);
        }
        tableDataInfo.setRows(rows);
        return AjaxResult.success(tableDataInfo);
    }





















    /**
     * 将时段区间转成单个时段
     * @param timeFramesVO
     * @param mapTime
     */
    private void timeFramesVOToMap(TimeFramesVO timeFramesVO,Map<String,String> mapTime){
         String startTime= timeFramesVO.getStartTime();
         String endTime=timeFramesVO.getEndTime();
        Integer start=time_sort.get(startTime);
        Integer end=time_sort.get(endTime);
        if(null!=start&&null!=endTime){

            if(end>=start){
                //不跨凌晨0点
                for(int i=start;i<=end;i++){
                    String str=  sort_time.get(i);
                    mapTime.put(str,str);
                }
            }else{
                //跨凌晨0点
                for(int i=start;i<=48;i++){
                    String str=  sort_time.get(i);
                    mapTime.put(str,str);
                }
                for(int i=1;i<=end;i++){
                    String str=  sort_time.get(i);
                    mapTime.put(str,str);
                }
            }
        }
    }

    /**
     * 时间排序map
     */
    private static Map<String,Integer> time_sort=new LinkedHashMap<String,Integer>(){
        {
            put("00:00",1); put("00:30",2);
            put("01:00",3); put("01:30",4);
            put("02:00",5); put("02:30",6);
            put("03:00",7); put("03:30",8);
            put("04:00",9); put("04:30",10);
            put("05:00",11); put("05:30",12);
            put("06:00",13); put("06:30",14);
            put("07:00",15); put("07:30",16);
            put("08:00",17); put("08:30",18);
            put("09:00",19); put("09:30",20);
            put("10:00",21); put("10:30",22);
            put("11:00",23); put("11:30",24);
            put("12:00",25); put("12:30",26);
            put("13:00",27); put("13:30",28);
            put("14:00",29); put("14:30",30);
            put("15:00",31); put("15:30",32);
            put("16:00",33); put("16:30",34);
            put("17:00",35); put("17:30",36);
            put("18:00",37); put("18:30",38);
            put("19:00",39); put("19:30",40);
            put("20:00",41); put("20:30",42);
            put("21:00",43); put("21:30",44);
            put("22:00",45); put("22:30",46);
            put("23:00",47); put("23:30",48);
        }
    };
    /**
     * 时间排序map
     */
    private static Map<Integer,String> sort_time=new LinkedHashMap<Integer,String>(){
        {
            put(1,"00:00"); put(2,"00:30");
            put(3,"01:00"); put(4,"01:30");
            put(5,"02:00"); put(6,"02:30");
            put(7,"03:00"); put(8,"03:30");
            put(9,"04:00"); put(10,"04:30");
            put(11,"05:00"); put(12,"05:30");
            put(13,"06:00"); put(14,"06:30");
            put(15,"07:00"); put(16,"07:30");
            put(17,"08:00"); put(18,"08:30");
            put(19,"09:00"); put(20,"09:30");
            put(21,"10:00"); put(22,"10:30");
            put(23,"11:00"); put(24,"11:30");
            put(25,"12:00"); put(26,"12:30");
            put(27,"13:00"); put(28,"13:30");
            put(29,"14:00"); put(30,"14:30");
            put(31,"15:00"); put(32,"15:30");
            put(33,"16:00"); put(34,"16:30");
            put(35,"17:00"); put(36,"17:30");
            put(37,"18:00"); put(38,"18:30");
            put(39,"19:00"); put(40,"19:30");
            put(41,"20:00"); put(42,"20:30");
            put(43,"21:00"); put(44,"21:30");
            put(45,"22:00"); put(46,"22:30");
            put(47,"23:00"); put(48,"23:30");
        }
    };
}
